package com.gao.util;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.gao.config.security.domain.LoginUser;
import io.jsonwebtoken.*;
import org.springframework.security.core.userdetails.UserDetails;

import javax.crypto.spec.SecretKeySpec;
import javax.xml.bind.DatatypeConverter;
import java.security.Key;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author gao
 * @date 2022/07/19 21:43:25
 */
public class JwtUtils {

    private static final String SECRET = "mysecret";
    private static final SignatureAlgorithm signatureAlgorithm = SignatureAlgorithm.HS256;

    private static Key getkey() {
        byte[] apiKeySecretBytes = DatatypeConverter.parseBase64Binary(SECRET);
        return new SecretKeySpec(apiKeySecretBytes, signatureAlgorithm.getJcaName());
    }

    public static String createToken(String permissionsJson, int expireSeconds) {

        // 组合header
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("alg", "HS256");
        map.put("typ", "JWT");
        JwtBuilder builder = Jwts.builder();
        builder.setHeaderParams(map);

        // 有效荷载，存放了用户名
        builder.claim("permissionsJson", permissionsJson);

        // 生成第三部分
        builder.signWith(SignatureAlgorithm.HS256, getkey());

        // 签发时间
        long nowMillis = System.currentTimeMillis();
        Date now = new Date(nowMillis);

        // 设置过期时间
        if (expireSeconds >= 0) {
            long expMillis = nowMillis + expireSeconds * 1000;
            Date expDate = new Date(expMillis);
            builder.setExpiration(expDate);
        }
        builder.setIssuedAt(now);

        String token = builder.compact();
        return token;
    }

    public static boolean verifyToken(String token) {
        Claims body = null;
        try {
            body = Jwts.parser().setSigningKey(getkey()).parseClaimsJws(token).getBody();
        } catch (ExpiredJwtException e) {
            e.printStackTrace();
            return false;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
        return body != null;
    }

    public static List<String> getPermissions(String token) {
        Claims body = null;
        try {
            body = Jwts.parser().setSigningKey(getkey()).parseClaimsJws(token).getBody();
            String permissionsJson = (String) body.get("permissionsJson");
            ObjectMapper objectMapper = new ObjectMapper();
            List permissions = objectMapper.readValue(permissionsJson, List.class);
            return permissions;
        } catch (ExpiredJwtException e) {
            throw new RuntimeException("超时", e);
        } catch (Exception e) {
            throw new RuntimeException("未知错误", e);
        }

    }
}